// utils/http.ts

// 定义基础配置
const BASE_URL = 'https://your-api-domain.com/api'
const DEFAULT_TIMEOUT = 15000

// 请求队列（用于防止重复请求）
const requestQueue = new Map()

// 请求拦截器类型
type RequestInterceptor = (config: RequestConfig) => RequestConfig | Promise<RequestConfig>
// 响应拦截器类型
type ResponseInterceptor = (response: any) => any | Promise<any>

interface RequestConfig {
  url: string
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
  data?: any
  params?: any
  header?: Record<string, string>
  loading?: boolean
  loadingText?: string
  timeout?: number
}

// 创建请求实例
const createRequest = () => {
  const interceptors = {
    request: [] as RequestInterceptor[],
    response: [] as ResponseInterceptor[]
  }

  // 添加拦截器
  const useRequestInterceptor = (...fns: RequestInterceptor[]) => {
    interceptors.request.push(...fns)
  }
  
  const useResponseInterceptor = (...fns: ResponseInterceptor[]) => {
    interceptors.response.push(...fns)
  }

  // 核心请求方法
  const request = async <T = any>(config: RequestConfig): Promise<T> => {
    // 请求唯一标识（防止重复请求）
    const requestKey = `${config.url}_${JSON.stringify(config.data || config.params)}`
    
    // 检查重复请求
    if (requestQueue.has(requestKey)) {
      return Promise.reject(new Error('重复请求已阻止'))
    }
    requestQueue.set(requestKey, true)

    try {
      // 合并配置
      const mergedConfig: RequestConfig = {
        method: 'GET',
        loading: true,
        timeout: DEFAULT_TIMEOUT,
        ...config,
        header: {
          'Content-Type': 'application/json',
          ...(config.header || {})
        }
      }

      // 请求拦截
      let finalConfig = mergedConfig
      for (const interceptor of interceptors.request) {
        finalConfig = await interceptor(finalConfig)
      }

      // 显示Loading
      if (finalConfig.loading) {
        uni.showLoading({
          title: finalConfig.loadingText || '加载中...',
          mask: true
        })
      }

      // 发起请求
      const [error, res] = await uni.request({
        url: BASE_URL + finalConfig.url,
        method: finalConfig.method,
        data: finalConfig.data,
        header: finalConfig.header,
        timeout: finalConfig.timeout
      })

      // 响应拦截
      let responseData = res?.data
      for (const interceptor of interceptors.response) {
        responseData = await interceptor(responseData)
      }

      // 业务状态码判断（根据后端API结构调整）
      if (responseData?.code !== 200) {
        throw new Error(responseData?.message || '请求失败')
      }

      return responseData.data as T
    } catch (error) {
      // 统一错误处理
      handleError(error)
      throw error
    } finally {
      // 清除请求标记
      requestQueue.delete(requestKey)
      uni.hideLoading()
    }
  }

  return {
    request,
    useRequestInterceptor,
    useResponseInterceptor
  }
}

// 统一错误处理
const handleError = (error: any) => {
  const errMsg = error.message || '网络错误'
  uni.showToast({
    title: errMsg,
    icon: 'none',
    duration: 3000
  })
  
  // 401跳转登录页
  if (error.statusCode === 401) {
    uni.redirectTo({ url: '/pages/login/login' })
  }
}

// 创建默认实例
const http = createRequest()

// 添加请求拦截器（示例：添加Token）
http.useRequestInterceptor((config) => {
  const token = uni.getStorageSync('token')
  if (token) {
    config.header = {
      ...config.header,
      Authorization: `Bearer ${token}`
    }
  }
  return config
})

// 添加响应拦截器（示例：处理数据结构）
http.useResponseInterceptor((response) => {
  if (response?.data?.token) {
    uni.setStorageSync('token', response.data.token)
  }
  return response
})

export default http